package database

import (
	"context"
	"fmt"
	"os"

	"github.com/jackc/pgx/v5"
	"github.com/spf13/viper"
)

var DB *pgx.Conn

func Init() {
	//数据库地址url
	//url := "postgres://testuser:123456@localhost:5432/luntan"
	dbInfo := fmt.Sprintf("postgres://%s:%s@%s:%d/%s",
		viper.GetString("database.user"),
		viper.GetString("database.password"),
		viper.GetString("database.host"),
		viper.GetInt("database.port"),
		viper.GetString("database.dbname"))
	var err error
	DB, err = pgx.Connect(context.Background(), dbInfo)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
		os.Exit(1)
	}
}
